<template>
  <n-scrollbar x-scrollable style="max-height: 100vh">
    <CommonPage show-footer>
        <div>
            <n-form ref="form"
                    :model="searchCondition"
                    :show-require-mark="false"
                    label-align="right"
                    label-placement="left"
                    label-width="80px">
                <div>
                    <div class="grid md:flex md:flex-wrap md:gap-x-1">
                        <n-form-item>
                            <lable>仓库名：</lable>
                            <n-select
                                v-model:value="searchCondition.storeId"
                                :options="stores"
                                clearable
                                placeholder="选择类型"
                                filterable
                            />
                        </n-form-item>
                        <n-form-item style="margin-left: 10px">
                            <label style="width: 50px;">创建人:</label>
                            <n-select v-model:value="searchCondition.adminId" :options="admins" filterable clearable/>
                        </n-form-item>
                        <n-form-item style="margin-left: 10px">
                            <label>采购时间：</label>
                            <n-date-picker v-model:value="timeRange" type="daterange" clearable/>
                        </n-form-item>
                        <n-form-item style="margin-left: 10px">
                            <label>状态：</label>
                            <n-select
                                v-model:value="searchCondition.status"
                                :options="statusOptions"
                                placeholder="选择类型"
                                filterable
                                clearable
                            />
                        </n-form-item>
                        <n-form-item style="margin-left: 10px">
                            <label>产品名：</label>
                            <n-input
                                v-model:value="searchCondition.productName"
                                placeholder="输入产品名"
                                style="width: 150px;"
                                clearable
                            >
                            </n-input>
                        </n-form-item>
                        <n-form-item style="margin-left: 10px">
                            <n-button type="primary" @click="searchByCondition">
                                筛选
                            </n-button>
                        </n-form-item>
                        <n-form-item style="margin-left: 10px">
                            <n-button type="primary" @click="showForm=true">
                                添加采购计划
                            </n-button>
                        </n-form-item>
                        <n-form-item style="margin-left: 10px">
                            <n-button type="error" @click="deleteSelectPurchasePlans">
                                批量删除
                            </n-button>
                        </n-form-item>
                      <n-form-item style="margin-left: 10px">
                        <n-button @click="exportListInfo"
                                  type="primary">
                          导出
                        </n-button>
                      </n-form-item>
                    </div>
                </div>
            </n-form>
        </div>
      <AddPlanForm
          :option="option"
          @update-page="searchByCondition"
          :show="showForm"
          :onClose="handleClose" />
      <UpdatePlan
          :option="option"
          @update-page="searchByCondition"
          :show1="showForm1"
          :onClose="handleClose"
          :attribute="currentAttribute"
      />
      <AuditingPlan
          :option="option"
          @update-page="searchByCondition"
          :show1="showForm2"
          :onClose="handleClose"
          :attribute="currentAttribute"
      />
      <n-data-table
            remote
            :single-line="false"
            ref="table"
            :columns="columns"
            :data="purchasePlanList"
            :loading="loading"
            :pagination="paginationReactive"
            :row-key="rowKey"
            :scroll-x="900"
            @update:checked-row-keys="handleCheck"
        />
    </CommonPage>
  </n-scrollbar>
</template>

<script setup>
import {h, onMounted, reactive, ref} from 'vue'
import api from '@/api/admin';
import {useUserStore} from '@/store';
import {useRouter} from 'vue-router';
import {formatDate} from "@/utils";
import PurchaseActions from "@/views/admin/category/components/category-actions.vue";
import AddPlanForm from './components/plan-add.vue'
import UpdatePlan from './components/plan-edit.vue'
import AuditingPlan from './components/plan-auditing.vue'
import {NTag} from "naive-ui";

const userStore = useUserStore()
const id=userStore.getId()
const router = useRouter()
const admins = ref([])
const option = ref([])
const currentAttribute = ref(null); // 当前编辑的属性
admins.value.push({
    label:'全部',
    value:-1,
})
const stores = ref([])
stores.value.push({
    label:'全部',
    value:-1,
})
const showForm=ref(false)
const showForm1=ref(false)
const showForm2=ref(false)
const handleClose=()=>{
  showForm.value=false;
  showForm1.value=false;
  showForm2.value=false;
};
const statusOptions=ref([
  {
    label:'全部',
    value:'全部',
  },
  {
    label: '未通过',
    value:'未通过',
  },
  {
    label:'未进行',
    value: '未进行',
  },
  {
    label: '进行中',
    value: '进行中',
  },
  {
    label: '已完成',
    value: '已完成',
  }
])
const loading = ref(true)
const purchasePlanList = ref([])
const range = ref([118313526e4, Date.now()]);
const checkedRowKeysRef = ref([]);
const handleStatusClick = async (purchasePlan) => {
  currentAttribute.value = purchasePlan; // 设置当前编辑的属性
  showForm2.value = true; // 显示编辑窗口
}
const columns = [
  {
    type: 'selection',
    fixed: 'left',
  },
  {
    key: 'colId',
    title: '序号',
    width: 60,
  },
  {
    key: 'productName',
    title: '产品',
    width: 200,

  },
  {
    key: 'quantity',
    title: '采购数量',
    width: 100,
  },
  {
    key: 'storeName',
    title: '仓库',
    width: 100,

  },
  {
    key: 'price',
    title: '计划金额',
    width: 80,
  },
  {
    key: 'planTime',
    title: '计划采购时间',
    width: 100,

  }
  ,
  {
    key: 'adminName',
    title: '负责人',
    width: 100,

  }
  ,
  {
    key: 'status',
    title: '状态',
    width: 80,
    render(row) {
      if (row.status === "批准") {
        return h(
            NTag,
            {
              type: 'success',
              bordered: false
            },
            {
              default: () => '批准'
            }
        );
      } else if (row.status === "驳回") {
        return h(
            NTag,
            {
              type: 'error',
              bordered: false
            },
            {
              default: () => '驳回'
            }
        );
      } else if (row.status === "待审核") {
        return h(
            NTag,
            {
              type: 'info',
              bordered: false,
              style: { cursor: 'pointer' },
              onClick: () => handleStatusClick(row)
            },
            {
              default: () => '待审核'
            }
        );
      }
    }
  },
  {
    key: 'operation',
    title: '操作',
    width: 120,
    render(row) {
      if (row.status === "待审核") {
        return h(
            PurchaseActions,
            {
              onClickDelete: () => onDeletePurchasePlan(row),
              onClickEdit: () => onEditPurchasePlan(row),
            }
        );
      }
    }
  },
]
const handleCheck = (rowKeys) => {
    checkedRowKeysRef.value = rowKeys;
}
const searchCondition = ref({
    adminId: -1,
    storeId: -1,
    status: '全部',
    productName: '',
    timeFrom: '',
    timeTo: ''
});
const timeRange = ref(null)
let total = 0
const paginationReactive = reactive({
  page: 1,
  pageSize: 50,
  showSizePicker: true,
  pageSizes: [50, 100, 150],
  itemCount: 0,
  prefix: () => {
    return '查询出 ' + total + '条记录';
  },
  onChange: (page) => {
    paginationReactive.page = page;
    queryByPage()
  },
  onUpdatePageSize: (pageSize) => {
    paginationReactive.pageSize = pageSize;
    paginationReactive.page = 1;
    queryByPage()
  }
});
const deleteSelectPurchasePlans = () => {
  if (checkedRowKeysRef.value.length <= 0) {
    $message.error("当前并未选择采购计划！")
    return
  }
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前所选采购计划？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const ids = checkedRowKeysRef.value.join(",")
      console.log(ids)
      loading.value = true
      try {
        const res = await api.deletePurchasePlans({ params: { ids } })
        if (res.code === 200) {
          $message.success("删除所选采购计划成功！")
          // await queryByPage()
          await searchByCondition()
        } else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除所选采购计划失败！")
      } finally {
        loading.value = false
      }
    },
  })
}
const searchByCondition = async () => {
  if (timeRange.value !== null) {
    searchCondition.value.timeFrom = formatDate(timeRange.value[0])
    searchCondition.value.timeTo = formatDate(timeRange.value[1])
  }else {
    // 如果时间范围选择器的值为 null，则将 timeFrom 和 timeTo 设置为 null
    searchCondition.value.timeFrom = null;
    searchCondition.value.timeTo = null;
  }
  console.log(searchCondition.value.timeFrom)
  console.log(searchCondition.value.timeTo)
  loading.value = true
  try {
    paginationReactive.page = 1;
    const res = await api.findPagePurchasePlan({
        params: {
            ...searchCondition.value,
            pageNum: paginationReactive.page,
            pageSize: paginationReactive.pageSize,
        }
    })
    if (res.code === 200) {
      total = res.data.total
      paginationReactive.itemCount = total
      purchasePlanList.value = res.data.records.map((item, i) => {
        return {
          ...item,
          colId: i + 1 + (paginationReactive.page - 1) * paginationReactive.pageSize
        }
      })
    } else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("查询采购计划失败！")
  } finally {
    loading.value = false
  }
}
const onDeletePurchasePlan = async (log) => {
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前采购计划？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const {id} = log
      loading.value = true
      try {
        const res = await api.deletePurchasePlan({id})
        if (res.code === 200) {
          $message.success("删除采购计划成功！")
          // await queryByPage()
          await searchByCondition()
        } else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除采购计划失败！")
      } finally {
        loading.value = false
      }
    }
  })
}

const onEditPurchasePlan = async (purchasePlan) => {
  currentAttribute.value = purchasePlan; // 设置当前编辑的属性
  console.log(currentAttribute.value.planTime)
  showForm1.value = true; // 显示编辑窗口
}

const queryAdminList = async () => {
  loading.value = true
  try {
    const res = await api.findAdminByRole({
      role: 'PURCHASEADMIN'
    })
    if (res.code === 200) {
      res.data.map((item) => {
        admins.value.push({
          label: item.name,
          value: item.id
        })
      })
    } else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取管理员信息失败！")
  } finally {
    loading.value = false
  }
}
const queryStoreList = async () => {
    loading.value = true
    try {
        const res = await api.findAllStore()
        if(res.code === 200) {
            res.data.map((item)=>{
                stores.value.push({
                    label: item.name,
                    value: item.id
                })
            })
        }
        else {
            $message.error(res.message)
        }
    } catch (err) {
        $message.error("获取仓库信息失败！")
    }finally{
        loading.value = false
    }
}

const queryByPage = async () => {
  loading.value = true
  try {
    const res = await api.findPagePurchasePlan(
        {
          params: {
            pageNum: paginationReactive.page,
            pageSize: paginationReactive.pageSize,
          }
        })
    if (res.code === 200) {
      total = res.data.total
      paginationReactive.itemCount = total
      purchasePlanList.value = res.data.records.map((item, i) => {
        return {
          ...item,
          colId: i + 1
        }
      })
      $message.success("获取采购计划成功！")
    } else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取采购计划失败！")
  } finally {
    loading.value = false
  }
}
const exportListInfo = async () => {
  const res = await api.exportPurchasePlanList({
    storeId:searchCondition.value.storeId,
    adminId:searchCondition.value.adminId,
    status: searchCondition.value.status,
    productName: searchCondition.value.productName,
    timeFrom: searchCondition.value.timeFrom,
    timeTo: searchCondition.value.timeTo,
  });
  const contentDisposition = res.headers["content-disposition"]
  let original_fileName = ""
  if(contentDisposition) {
    const uri = res.headers["content-disposition"].split("=")[1]
    original_fileName = window.decodeURI(uri)
  }
  const blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
  if(window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, original_fileName);
  } else{
    const fileName = original_fileName;
    const elink = document.createElement('a')
    document.body.appendChild(elink)
    elink.download= fileName;
    elink.style.display ="none"
    elink.href  = window.URL.createObjectURL(blob)
    elink.click()
    window.URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }
}
const rowKey = (rowData) => {
  return rowData.id
}
onMounted(() => {
  queryStoreList()
  queryAdminList()
  queryByPage()
})
</script>
<style scoped>
:deep(.n-data-table-th__title),
:deep(.n-data-table-td) {
  text-align: center;

}

:deep(.n-select) {
  width: 140px !important;
}

:deep(.two-line-description) {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2; /* 控制显示的行数 */
  overflow: hidden;
}

.search-container {
  display: flex;
  align-items: center;
  border: 1px solid rgba(217, 217, 217, 0.33);
  border-radius: 6px;
  overflow: hidden;
  margin-left: 10px;
  margin-top: -77px;
}

.search-container .n-select {
  width: 100px;
  border-right: 1px solid rgba(217, 217, 217, 0.33);
}

.search-container .n-input {
  flex-grow: 1;
}

.search-icon {
  width: 20px;
  height: 20px;
  cursor: pointer;
}
</style>
